//
//  UserAccountViewModel.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/9.
//  Copyright © 2015年 hzj. All rights reserved.
//

import UIKit
import ReactiveCocoa

class UserAccountViewModel: NSObject {
//单例
    static let sharedUserAccountViewModel = UserAccountViewModel()
    
    override init() {
        
        userAccount = UserAccount.loadTheUserAccount()
    }
    //模型
    private var userAccount : UserAccount?
    //只读token
    
    var access_token:String?  {
        
        return userAccount?.access_token

    }
    //头像
    var avatarlarge:NSURL?{
        return  NSURL(string:userAccount?.avatar_large ?? "")
    }
    ///是否登录
    var isLogin:Bool{
        return userAccount?.access_token != nil
    }
    
    
    //根据得到的code进行网络请求，以或得更多用户信息
    
    func loadTheUserAccount(code:String) ->RACSignal{
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            
            NetworkTool.sharedTool.loadTheToken(code).doNext({ (result) -> Void in

             
                //字典转模型
                let account = UserAccount(dict: result as! [String : AnyObject])
                self.userAccount = account
//                printLog(account)
                
                //用包含token的返回值请求更多信息
//                self.getTheUserInfo(account)

                
                NetworkTool.sharedTool.loadTheUserInfo(account.uid!).subscribeNext({ (result) -> Void in
                    
                    let dic = result as! [String:AnyObject]
                    account.name = dic["name"] as? String
                    account.avatar_large = dic["avatar_large"] as? String
                    
                    printLog("好好的\(account)")
                    
                    account.saveTheUserAccount()
                    
                    // 通知订阅者网络数据加载完成
                    subscriber.sendCompleted()
                    
                    /*
                    //只能获取到name和avatar_large
                    let userinfo = UserAccount(dict: result as! [String : AnyObject])
                    printLog(userinfo)
                    */
                    
                    }, error: { (error) -> Void in
                        printLog(error, logError: true)
                    }) { () -> Void in
                        
                }

                
            }).subscribeError({ (error) -> Void in
                subscriber.sendError(error)
            })
            
        
            return nil
        })
    }

    
    
}
